<template>
    <section>
        <!--工具条-->
        <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
            <!--
            :inline="true"：行内表单
            :model="searchForm" 双向绑定公共前缀
            -->
            <el-form :inline="true" :model="searchForm">
                <el-form-item label="部门">
                    <el-input v-model="searchForm.name" placeholder="部门"></el-input>
                </el-form-item>
                <el-form-item label="状态">
                    <el-select v-model="searchForm.state" clearable  placeholder="请选择状态">
                        <el-option label="启用" value="1"></el-option>
                        <el-option label="禁用" value="0"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="searchFormDepartments" >查询</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleAdd">新增</el-button>
                </el-form-item>
            </el-form>
        </el-col>
        <!--列表-->
        <el-table :data="departments"  @selection-change="selsChange"  v-loading="listLoading" style="width: 100%;">
            <!--显示多选框-->
            <el-table-column type="selection" width="55">
            </el-table-column>
            <el-table-column prop="name" label="部门" >
            </el-table-column>
            <el-table-column prop="sn" label="编号" >
            </el-table-column>
            <el-table-column prop="state" label="状态">
                <template scope="scope">
                    <span style="color: green" v-if="scope.row.state==1">启用</span>
                    <span style="color: red" v-else-if="scope.row.state==0">禁用</span>
                </template>
            </el-table-column>
            <el-table-column prop="manager.username" label="部门经理" >
            </el-table-column>
            <el-table-column prop="parent.name" label="上级部门" >
            </el-table-column>
            <el-table-column label="操作" >
                <template scope="scope">
                    <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                    <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!--工具条-->
        <el-col :span="24" class="toolbar">
            <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
            <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="pageSize" :total="total" style="float:right;">
            </el-pagination>
        </el-col>


        <!--新增/修改弹出框-->
        <el-dialog :title="title" :visible.sync="addFormVisible" >
            <!--
                ref:简单理解就是申明form表单的id
                :rules:定义校验规则
             -->
            <el-form ref="form" :rules="rules"  :model="form" label-width="80px">
                <el-form-item label="部门名" prop="name" >
                    <el-input v-model="form.name"></el-input>
                </el-form-item>
                <el-form-item label="部门编号" prop="sn">
                    <el-input v-model="form.sn"></el-input>
                </el-form-item>
                <el-form-item label="状态">
                    <el-radio-group v-model="form.state">
                        <el-radio :label="1">启用</el-radio>
                        <el-radio :label="0">禁用</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="部门经理" prop="managerId">
                    <el-select v-model="form.managerId" placeholder="请选择">
                        <el-option
                                v-for="item in managers"
                                :key="item.id"
                                :label="item.username"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="上级部门">
                    <el-cascader v-model="form.path"
                            :options="parents"
                            :props="{ checkStrictly: true }"
                            clearable></el-cascader>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click.native="addFormVisible = false">取消</el-button>
                <el-button type="primary" @click="addSubmit" >提交</el-button>
            </div>
        </el-dialog>
    </section>
</template>
<script>
    export default {
        data() {
            return {
                /*定义校验规则*/
                rules: {
                    name: [
                        {required: true, message: '部门名必填!!', trigger: 'blur'}
                    ],
                    sn: [
                        {required: true, message: '部门编号必填!!', trigger: 'blur'}
                    ],
                    managerId: [
                        {required: true, message: '部门经理必选!!', trigger: 'blur'}
                    ]
                },
                //弹出框标题
                title:"",
                //弹出框默认是关闭状态
                addFormVisible:false,
                //上级部门
                parents:[],
                //高级查询form表单
                searchForm:{
                    //部门名
                    name:"",
                    //状态
                    state:""
                },
                //弹出框form中的属性
                form:{
                    id:"",
                    name:"",//部门名
                    sn:"",//编号
                    state:1,//状态
                    managerId:"",//部门经理
                    path:""//上级部门对应的值
                },
                //部门经理
                managers:[],
                //分页列表
                departments: [],
                //显示加载框
                listLoading: false,
                //记录复选框选中多少行
                sels: [],
                //当前页
                currentPage: 1,
                //每页条数
                pageSize: 10,
                //总条数
                total: 0
            };
        },
        methods:{
          /*  //格式化单元格
            formatState(row, column){
                return row.state == 1 ? "启用" : "禁用";
            },*/
            //选中复选框触发函数
            selsChange(rows){
                this.sels = rows;
            },
            //点击编辑框触发函数
            handleEdit(index,row){
                //修改标题
                this.title = "修改";
                //发送ajax请求，获取所有的部门经理
                this.loadManagers();
                //发送ajax请求，获取所有的上级部门
                this.loadParentDepartments();
                //回显数据（给普通属性赋值）
                for(let k in this.form){
                    this.form[k] = row[k];
                }
                //对于特殊属性单独赋值
                this.form["managerId"] = row.manager.id;
                //如果dirPath有值，就证明选择了上级部门
                if(row.dirPath){
                    this.form.path = row.dirPath.split(",");
                }
                //显示弹出框
                this.addFormVisible = true;
            },
            //点击删除按钮触发函数
            handleDel(index,row){
                this.$confirm('您确认离我而去吗?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.$http.delete("/department/" + row.id).then(res => {
                        let {success, message} = res.data;
                        if(success){
                            this.$message({
                                type: 'success',
                                message: '删除成功!'
                            });
                            //重新刷新页面
                            this.loadDepartments();
                        }else{
                            this.$message.error(message);
                        }
                    });
                }).catch(() => {
                });
            },
            //批量删除触发函数
            batchRemove(){
                this.$confirm('您确认离我而去吗?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.$http.post("/department/batchRemove",this.sels).then(res => {
                        let {success, message} = res.data;
                        if(success){
                            this.$message({
                                type: 'success',
                                message: '删除成功!'
                            });
                            //重新刷新页面
                            this.loadDepartments();
                        }else{
                            this.$message.error(message);
                        }
                    });
                }).catch(() => {
                });
            },
            //页码发生改变的时候触发函数
            handleCurrentChange(val){
                //重新修改页码
                this.currentPage = val;
                //重新加载列表
                this.loadDepartments();
            },
            //加载员工分页列表
            loadDepartments(){
                //分页传递参数
                let param = {
                    "currentPage": this.currentPage,
                    "pageSize": this.pageSize,
                    "name":this.searchForm.name,
                    "state":this.searchForm.state
                };
                this.$http.post("/department", param).then(res => {
                    let {data, totals} = res.data;
                    this.departments = data;
                    this.total = totals;
                });
            },
            //高级查询按钮
            searchFormDepartments(){
                //把页码重新设置到第一页
                this.currentPage = 1;
                //再次进行查询部门
                this.loadDepartments();
            },
            //查询所有的部门经理
            loadManagers(){
                this.$http.post("/employee").then(res => {
                    this.managers = res.data;
                });
            },
            //查询所有的上级部门
            loadParentDepartments(){
                this.$http.post("/department/queryTree").then(res => {
                    this.parents = res.data;
                });
            },
            //点击新增按钮触发事件
            handleAdd(){
                //清空校验
                //如果有校验，才清空校验
                if(this.$refs["form"]){
                    this.$refs["form"].resetFields();
                }
                //修改标题
                this.title = "新增";
                //发送ajax请求，获取所有的部门经理
                this.loadManagers();
                //发送ajax请求，获取所有的上级部门
                this.loadParentDepartments();
                //清空form表单中的数据
                for(var k in this.form){
                    this.form[k] = "";
                }
                //单独给状态赋值
                this.form.state = 1;
                //弹出窗体
                this.addFormVisible = true;
            },
            //保存/修改都是用此事件
            addSubmit(){
                //创建manager对象
                let manager = {"id": this.form.managerId};
                //添加属性
                this.form["manager"] = manager;
                //如果选择了上级部门，才走下面的流程
                if(this.form.path){
                    //添加属性   [1,2,3]
                    this.form["dirPath"] = this.form.path.toString();
                    //创建parent对象
                    let parent = {"id": this.form.path[this.form.path.length - 1]};
                    //添加属性
                    this.form["parent"] = parent;
                }else{
                    //如果没有选择上级部门，我就把这个属性设置为null
                    this.form["parent"] = null;
                    this.form["dirPath"] = "";
                }
                //在提交之前，form表单必须要先经过校验
                this.$refs["form"].validate((valid) => {
                    if (valid) {
                        //保存/修改 数据
                        this.$http.put("/department", this.form).then(res => {
                            let {success, message} = res.data;

                            if(success){
                                //关闭窗体
                                this.addFormVisible = false;
                                //刷新界面
                                this.loadDepartments();
                            }else{
                                this.$message.error(message);
                            }
                        });
                    }
                });


            }


        },
        mounted(){
            //调用分页列表
            this.loadDepartments();
        }
    };
</script>